import {Injectable} from '@angular/core';
import {AlertController, App, LoadingController, Platform, ToastController} from "ionic-angular";
import {Network} from "@ionic-native/network";

@Injectable()
export class PublicService {

  public hasZh = /^([\w\W]{0,})([\u4e00-\u9fa5]{1,})([\w\W]{0,})([\u4e00-\u9fa5]{1,})([\w\W]{0,})+$/;//至少含有两个中文
  public myreg = /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
  public isPhone = /^([0-9]{3,4}-)?[0-9]{7,8}$/;

  constructor(private toastCtrl: ToastController,
              private loadingCtrl: LoadingController,
              private alertCtrl: AlertController,
              private app: App,
              public plt: Platform,
              private network: Network) {

  }

  public presentToast(str) {
    let toast = this.toastCtrl.create({
      message: str,
      duration: 1500,
      position: 'middle',
      showCloseButton: false,
      closeButtonText: 'ok',
      dismissOnPageChange: true
    });
    toast.onDidDismiss(() => {
    });
    toast.present().then();
  }

  public presentLoadingDefault() {
    let loading = this.loadingCtrl.create({
      showBackdrop: false
    });
    return loading;
  }

  public presentLoadingToast(str) {
    let loading = this.loadingCtrl.create({
      spinner: 'hide',
      showBackdrop: false,
      duration: 1500,
      content: str,
    });
    loading.present();
    return loading;
  }

  public presentLoadingToastTime(str, duration) {
    let loading = this.loadingCtrl.create({
      spinner: 'hide',
      showBackdrop: false,
      content: str,
      duration: duration
    });
    loading.present();
    return loading;
  }

  public presentLoadingContentToast(str, duration) {
    let loading = this.loadingCtrl.create({
      showBackdrop: false,
      content: str,
      duration: duration
    });
    loading.present();
    return loading;
  }

  public presentConfirm(str): Promise<any> {
    const promise = new Promise((resolve, reject) => {
      let alert = this.alertCtrl.create({
        title: '提示',
        message: str,
        buttons: [
          {
            text: '取消',
            role: 'cancel',
            handler: () => {
            }
          },
          {
            text: '确定',
            handler: () => {
              resolve();
            }
          }
        ]
      });
      alert.present();
    });
    return promise;
  }


  public presentAlert(str): Promise<any> {
    const promise = new Promise((resolve, reject) => {
      let alert = this.alertCtrl.create({
        title: '提示',
        message: str,
        buttons: [{
          text: '确定',
          handler: () => {
            resolve();
          }
        }]
      });
      alert.present();
    });
    return promise;
  }


  /**
   *
   * @param str  提示内容
   * @param text1 //按钮文本
   * @param text2 //按钮文本
   * @returns {Promise<T>}
   */
  public presentCustomConfirm(str, text1, text2): Promise<any> {
    const promise = new Promise((resolve, reject) => {
      let alert = this.alertCtrl.create({
        title: '提示',
        message: str,
        buttons: [{
          text: text1,
          role: 'cancel',
          handler: () => {
            reject();
          }
        },
          {
            text: text2,
            handler: () => {
              resolve();
            }
          }]
      });
      alert.present();
    });
    return promise;
  }

  public setAppRootPage(obj) {
    this.app.getRootNav().setRoot(obj);
  }

  /**
   * 格式化日期yyyy-mm-dd
   * @param d
   * @param interval  间隔天数
   * @returns {string}
   */
  public getDate(date: Date, interval: number) {
    date.setDate(date.getDate() + interval);
    let year = date.getFullYear();
    let month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
    let day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
    return year + "-" + month + "-" + day;
  }



  /**
   * 格式化时间
   * yyyy-mm-dd HH:mm:ss
   * @param d
   * @returns {string}
   */
  public getTime(date: Date) {
    let year = date.getFullYear();
    let month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
    let day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
    let hour = date.getHours() > 9 ? date.getHours() : "0" + date.getHours(); //获取当前小时数(0-23)
    let minute = date.getMinutes() > 9 ? date.getMinutes() : "0" + date.getMinutes(); //获取当前分钟数(0-59)
    let seconds = date.getSeconds() > 9 ? date.getSeconds() : "0" + date.getSeconds(); //获取当前秒数(0-59)
    return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + seconds;
  }

  /**
   *格式化时间
   * yyyy-mm-dd HH:mm
   * @param d
   * @param interval 60*60*1000
   * @returns {string}
   */
/*  public getYMDHM(date: Date, interval: number) {
    date.setTime(date.getTime() + interval);
    let year = date.getFullYear();
    let month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
    let day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
    let hour = date.getHours() > 9 ? date.getHours() : "0" + date.getHours(); //获取当前小时数(0-23)
    let minute = date.getMinutes() > 9 ? date.getMinutes() : "0" + date.getMinutes(); //获取当前分钟数(0-59)
    return year + "-" + month + "-" + day + " " + hour + ":" + minute;
  }*/


  public getYMDHM(d: Date, interval: number) {
    let date=new Date();
    date.setTime(d.getTime() + interval);
    let year = date.getFullYear();
    let month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
    let day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
    let hour = date.getHours() > 9 ? date.getHours() : "0" + date.getHours(); //获取当前小时数(0-23)
    let minute = date.getMinutes() > 9 ? date.getMinutes() : "0" + date.getMinutes(); //获取当前分钟数(0-59)
    return year + "-" + month + "-" + day + " " + hour + ":" + minute;
  }

  /**
   *当前时间 HH:MM
   * date 日期
   * interval 60*60*1000 间隔
   * @returns {string}
   */
  public getCurrentHM(date: Date,interval: number) {
    date.setTime(date.getTime() + interval);
    let hour = date.getHours() > 9 ? date.getHours() : "0" + date.getHours(); //获取当前小时数(0-23)
    let minute = date.getMinutes() > 9 ? date.getMinutes() : "0" + date.getMinutes(); //获取当前分钟数(0-59)
    return hour + ":" + minute;
  }


  /**
   * 字符串转日期
   * @param date  yyyy-mm-dd HH:mm
   */
  public stringToDate(date: string) {
    var fullDate = date.slice(0, 10).split("-");
    var fullTime = date.slice(11, 16).split(":");
    let year = Number.parseInt(fullDate[0]);
    let month = Number.parseInt(fullDate[1]) - 1;
    let day = Number.parseInt(fullDate[2]);
    let hour = Number.parseInt(fullTime[0]);
    let minute = Number.parseInt(fullTime[1]);
    return new Date(year, month, day, hour, minute, 0);
  }

  /**
   * 生成格式YYYYMMDDHHMMSS格式数据
   * @param d
   * @returns {string}
   */
  public getTimeLine(date: Date) {
    let year = date.getFullYear();
    let month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
    let day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
    let hour = date.getHours() > 9 ? date.getHours() : "0" + date.getHours(); //获取当前小时数(0-23)
    let minute = date.getMinutes() > 9 ? date.getMinutes() : "0" + date.getMinutes(); //获取当前分钟数(0-59)
    let seconds = date.getSeconds() > 9 ? date.getSeconds() : "0" + date.getSeconds(); //获取当前秒数(0-59)
    return year + "" + month + "" + day + "" + hour + "" + minute + "" + seconds;
  }

  /**
   * 是否为空
   * @param str
   */
  public isEmpty(str: any) {
    if (typeof(str) == "undefined") {
      return true;
    } else if (typeof(str) == "string") {
      if (str && str != '' && str.length > 0) {
        return false;
      } else {
        return true;
      }
    } else if (typeof(str) == "number") {
      if (str == 0) {
        return true;
      } else {
        return false;
      }
    }
  }

  /**
   * 判断网络连接
   */
  networkConnect() {
    if (this.network.type === 'none') {
      return false;
    } else {
      return true;
    }
  }


  /**
   * 是否真机环境
   * @return {boolean}
   */
  isMobile(): boolean {
    return this.plt.is('mobile');
    //return this.plt.is('mobile') && !this.plt.is('mobileweb');
  }

  /**
   * 是否android真机环境
   * @return {boolean}
   */
  isAndroid(): boolean {
    return this.isMobile() && this.plt.is('android');
  }

  /**
   * 是否ios真机环境
   * @return {boolean}
   */
  isIos(): boolean {
    return this.isMobile() && (this.plt.is('ios') || this.plt.is('ipad') || this.plt.is('iphone'));
  }

  /**
   * 暂停
   * 需要配合方法的 async
   * @param ms
   */
  sleep(ms: number) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}
